package ar.edu.itba.it.pdc.proxy.stats;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.joda.time.DateTime;

public class StatisticsCollector {

	private Map<String, ClientStatistics> statistics;
	
	public StatisticsCollector(){
		this.statistics = new HashMap<String, ClientStatistics>();
	}
	
	public long getBytesSent(String username){
		return this.statistics.get(username).getBytesSent();
	}
	
	public long getBytesReceived(String username){
		return this.statistics.get(username).getBytesReceived();
	}
	
	public long getMailsRead(String username){
		return this.statistics.get(username).getMailsRead();
	}

	public long getMailsDeleted(String username){
		return this.statistics.get(username).getMailsDeleted();
	}
	
	public List<DateTime> getAccesses(String username){
		if (!this.statistics.containsKey(username))
			return null;
		
		return this.statistics.get(username).getAccesses();
	}
	
	public int getAccessesQuantity(String username){
		if (!this.statistics.containsKey(username))
			return 0;
		
		return this.statistics.get(username).getAccesses().size();		
	}
	
	public long getTotalBytesSent(){
		long ans = 0;
		for (Entry<String, ClientStatistics> e : this.statistics.entrySet())
			ans += e.getValue().getBytesSent();
		return ans;
	}
	
	public long getTotalBytesReceived(){
		long ans = 0;
		for (Entry<String, ClientStatistics> e : this.statistics.entrySet())
			ans += e.getValue().getBytesReceived();
		return ans;
	}
	
	private ClientStatistics addLoggedUser(String username){
		return this.statistics.put(username, new ClientStatistics());
	}
	
	public void collectBytes(String username, long sent, long received){
		if (!this.statistics.containsKey(username))
			addLoggedUser(username);
		
		ClientStatistics stats = this.statistics.get(username);
		stats.incrementBytesSentBy(sent);
		stats.incrementBytesReceivedBy(received);
	}
	
	public void addAccess(String username, DateTime date){
		if (!this.statistics.containsKey(username))
			addLoggedUser(username);
		
		ClientStatistics stats = this.statistics.get(username);
		stats.addAccess(date);
	}
	
	public void incrementBytesSentBy(String username, int n){
		this.statistics.get(username).incrementBytesSentBy(n);
	}
	
	public void incrementBytesReceivedBy(String username, int n){
		this.statistics.get(username).incrementBytesReceivedBy(n);
	}
	
	public void oneMoreMailReadBy(String username){
		this.statistics.get(username).incrementMailsReadBy(1);
	}
	
	public void oneMoreMailDeletedBy(String username){
		this.statistics.get(username).incrementMailsDeletedBy(1);
	}
	
	public boolean hasLogged(String username){
		return this.statistics.containsKey(username);
	}
}
